"""
公共工具方法
"""
import random

from tests.utils.logUtil import log


def validate_response(response, expected_code, expected_msg, expected_status_code=200):
    """
    通用校验结果
    :param response: 请求结果对象
    :param expected_code: 预期错误码
    :param expected_msg: 预期错误信息
    :param expected_status_code: 预期状态码
    :return: None
    """
    # Validate HTTP status code
    assert response.status_code == expected_status_code, f"Unexpected status code: {response.status_code}"

    try:
        # Parse response content as JSON
        data = response.json()
    except ValueError as e:
        raise ValueError(f"Failed to parse response as JSON: {e}")

    # Validate business code
    assert data.get("code") == expected_code, f"Unexpected code: {data.get('code')}"
    # Validate business message
    if expected_msg is not None:
        assert data.get("msg") == expected_msg, f"Unexpected message: {data.get('msg')}"


def verify_response(response, expected_result):
    """
    校验请求结果
    :param response: 请求结果对象
    :param expected_result: 预期结果，可以是字典或元组 (status_code, expected_code, expected_msg)
    :return: None
    """
    # 记录响应和预期结果类型日志
    log.info(f"response: {response} | expected_result: {expected_result} "
             f"| expected_result type {type(expected_result)}")

    # 根据预期结果类型解析预期的状态码、代码和消息
    if isinstance(expected_result, tuple) and len(expected_result) == 1 and isinstance(expected_result[0], dict):
        expected_dict = expected_result[0]
        status_code = expected_dict.get("status_code", 200)
        expected_code = expected_dict.get("code", None)
        expected_msg = expected_dict.get("msg", None)
    elif isinstance(expected_result, dict):
        expected_code = expected_result.get("code", None)
        expected_msg = expected_result.get("msg", None)
        status_code = expected_result.get("status_code", 200)
    else:
        # 如果预期结果类型不正确，抛出异常
        assert False, "expected_result must be a dictionary or a tuple of (status_code, expected_code, expected_msg)"

    # 校验HTTP状态码
    assert response.status_code == status_code, f"Unexpected status code: {response.status_code}"

    try:
        # 尝试将响应内容解析为JSON
        data = response.json()
    except ValueError as e:
        # 如果解析失败，断言错误
        assert False, f"Failed to parse response as JSON: {e}"

    # 获取业务代码
    code = data.get("code")

    # 打印调试信息
    log.info(f"code: {code}, expected_code: {expected_code}")

    # 校验业务代码
    assert code == expected_code, f"Unexpected code: {code}"

    # 如果预期消息不为空，则校验业务消息
    if expected_msg is not None:
        assert data.get("msg") == expected_msg, f"Unexpected message: {data.get('msg')}"


def random_get_namespace_id(data):
    """
    随机获取命名空间ID。

    本函数旨在从给定的数据字典中解析出命名空间列表，并随机选择一个命名空间ID返回。
    如果数据为空或命名空间列表为空，将返回默认的命名空间ID "public"。
    如果某个命名空间的 namespace 字段为空，则跳过该命名空间。

    :param data: 包含命名空间信息的数据字典。
    :return: 随机选择的命名空间ID，如果数据为空或无有效命名空间信息，则返回 "public"。
    """
    # 解析 data 列表
    namespace_data = data.get("data", [])

    # 过滤掉 namespace 字段为空的项
    valid_namespaces = [item for item in namespace_data if item.get("namespace")]

    if valid_namespaces:
        # 随机选择一个有效的元素
        selected_item = random.choice(valid_namespaces)

        # 获取 namespace 值
        namespace_value = selected_item.get("namespace")

        return namespace_value
    else:
        # 如果数据为空或无有效命名空间信息，返回默认的命名空间ID "public"
        return None
